import { notification } from "ant-design-vue";
import { Client } from "./ApiClient";
import jwtToken from "./jwtToken";
export default new Client(import.meta.env.VITE_API_URL, {
  async fetch(url, init) {
    let realUrl = `${url}`;
    const accessTokenLocal = jwtToken.getAccesstoken();
    if (init && accessTokenLocal) {
      init.headers = {
        ...init.headers,
        Authorization: `Bearer ${accessTokenLocal}`,
      };
    }
    const isExpired = jwtToken.getIsExpired();
    if (init && isExpired) {
      const refreshToken = jwtToken.getRefreshToken();
      init.headers = {
        ...init.headers,
        "X-Authorization": `Bearer ${refreshToken}`,
      };
    }
    return window
      .fetch(realUrl, init)
      .then(async (res) => {
        if (res.status === 404) {
          notification.error({
            style: { whiteSpace: "pre-wrap" },
            message: "404访问接口不存在",
            description: res.url,
          });
          return Promise.reject(res);
        }
        const resCopy = res.clone();
        jwtToken.checkAndStoreAuthentication(resCopy);
        const resJson = await resCopy.json();
        if (resJson?.errors) {
          notification.error({
            style: { whiteSpace: "pre-wrap" },
            message: `出错了,状态码:${resJson.statusCode}`,
            description: JSON.stringify(resJson?.errors),
          });
          return Promise.reject(resJson.errors);
        } else {
          return Promise.resolve(res);
        }
      })
      .catch((error) => {
        if (`${error}` === "TypeError: Failed to fetch") {
          notification.error({
            style: { whiteSpace: "pre-wrap" },
            message: `服务器停止服务了`,
            description: `Failed to fetch | 加载失败`,
          });
        }
        return Promise.reject(undefined);
      });
  },
});
